package com.zhouyu.postprocessor;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;

@Component
public class MyInstantiationPostProcessor implements InstantiationAwareBeanPostProcessor {

	@Override
	public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName)  {
		if (beanName.equals("favoriteService")) {
			Object instance=null;
			try {
				System.out.println("MyInstantiationPostProcessor#postProcessBeforeInstantiation");
				instance= beanClass.getConstructor().newInstance();
			}catch (Exception e){
			}

			return instance;
		}
		return null;
	}


	@Override
	public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
		if (beanName.equals("userService")) {
			System.out.println("MyInstantiationPostProcessor#postProcessAfterInstantiation");
		}
		return true;
	}

	@Override
	public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
		if (beanName.equals("userService")) {
			System.out.println("MyInstantiationPostProcessor#postProcessProperties");
		}
		return InstantiationAwareBeanPostProcessor.super.postProcessProperties(pvs, bean, beanName);
	}


	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		if (beanName.equals("userService")) {
			System.out.println("MyInstantiationPostProcessor#postProcessBeforeInitialization");
		}
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if (beanName.equals("userService")) {
			System.out.println("MyInstantiationPostProcessor#postProcessAfterInitialization");
		}
		return bean;
	}
}
